package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
	@Autowired
	private ElasticsearchTemplate elasticsearchTemplate;
	@Override
	public Map search(Map<String, String> searchMap) {
		Map<String,Object> resultMap = new HashMap<>();
		//构建查询
		if(searchMap!=null){
			NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
			BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
			//boolQueryBuilder.must()
			//1.关键字查询
			if(!StringUtils.isEmpty(searchMap.get("keywords"))){
				boolQueryBuilder.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")).operator(Operator.AND));
			}
			//高亮 自定义高亮区
			HighlightBuilder.Field field = new HighlightBuilder.Field("name")//高亮域
					.preTags("<span style='color:red'>")//高亮样式的前缀
					.postTags("</span>");//高亮样式的后缀
			nativeSearchQueryBuilder.withHighlightFields(field);
			//2.按照品牌查询
			if(StringUtils.isNotEmpty(searchMap.get("brand"))){
				boolQueryBuilder.filter(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
			}
			//6.价格区间查询
			if(StringUtils.isNotEmpty(searchMap.get("price"))){
				String[] p = searchMap.get("price").split("-");
				if(p.length==2){
					boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(p[1]));
				}
				boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(p[0]));
			}

			nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
			//3.根据品牌分组聚合查询
			String skuBrand = "skuBrand";
			nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName").size(10));
			//5.按照规格镜像聚合查询
			String skuSpec = "skuSpec";
			nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword").size(10));
			//4.按照规格进行过滤查询
			for (String key : searchMap.keySet()) {
				if(key.startsWith("spec_")){
					//为了搜索索引库，索引库中的保存数据是8+128这种的 所以%2B要转换成+
					String value = searchMap.get(key).replace("%2B","+");
					boolQueryBuilder.filter(QueryBuilders.termQuery("specMap." + key.substring(5) +".keyword",value));
				}
			}
			//8.排序查询
			if(!StringUtils.isEmpty(searchMap.get("sortField"))){
				if("ASC".equals(searchMap.get("sortRule"))){
					nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
				}else {
					nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));

				}
			}

			//7.可以添加一些分页的方法
			String pageNum = searchMap.get("pageNum");
			String pageSize = searchMap.get("pageSize");
			if(null==pageNum){
				pageNum="1";
			}
			if(pageSize==null){
				pageSize="20";
			}
			PageRequest of = PageRequest.of(Integer.parseInt(pageNum)-1, Integer.parseInt(pageSize));
			nativeSearchQueryBuilder.withPageable(of);
			//开启查询
			/**
			 * 第一个参数:条件构建对象
			 * 二:查询操作实体类
			 * 三:查询结果操作对象
			 */
			AggregatedPage<SkuInfo> resultInfos = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
				@Override
				public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {

					//查询结果操作
					List<T> list = new ArrayList<>();
					//获取查询命中结果数据
					SearchHits hits = searchResponse.getHits();
					if(hits!=null){
						//有结果集
						for (SearchHit hit : hits) {
							//将json数据转换为对象
							SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
							Map<String, HighlightField> highlightFields = hit.getHighlightFields();
							//StringBuilder stringBuilder = new StringBuilder();
							if (highlightFields != null && highlightFields.size()>0){
								//替换数据
								//stringBuilder.append(highlightFields.get("title").getFragments());
								// goods.setTitle(stringBuilder.toString());
								skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
							}

							list.add((T)skuInfo);
						}
					}
					return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(),searchResponse.getAggregations());
				}
			});
			//封装最终返回结果
			//总记录数
			resultMap.put("total",resultInfos.getTotalElements());
			//总页数
			resultMap.put("totalPages",resultInfos.getTotalPages());
			//查询结果集合

			resultMap.put("rows", resultInfos.getContent());
			//获取聚合品牌结果
			StringTerms brandTerms = (StringTerms) resultInfos.getAggregation(skuBrand);
			//流运算 比遍历效率高
			List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
//			List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
//
//			List brandList = new ArrayList();
//			for (Terms.Bucket bucket : buckets) {
//				Object key = bucket.getKey();
//				brandList.add(key);
//			}

			resultMap.put("brandList",brandList);
			//获取规格分组 封装
			StringTerms specTerms = (StringTerms) resultInfos.getAggregation(skuSpec);
			List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
			Map<String, Set<String>> stringSetMap = this.formartSpec(specList);
			resultMap.put("specList",stringSetMap);
			//返回当前页
			resultMap.put("pageNum",pageNum);
		}
		return resultMap;
	}
	public Map<String, Set<String>> formartSpec(List<String> specList){
		Map<String,Set<String>> resultMap = new HashMap<>();
		if(specList!=null&&specList.size()>0){
			for (String specJsonString : specList) {
				//将json数据转换为map
				Map<String,String> specMap = JSON.parseObject(specJsonString, Map.class);
				for (String specKey : specMap.keySet()) {
					Set<String> specSet = resultMap.get(specKey);
					if(specSet==null){
						specSet = new HashSet<String>();
					}
					//将规格的值放入set中
					specSet.add(specMap.get(specKey));
					resultMap.put(specKey,specSet);
				}
			}
		}
		return resultMap;
	}
}
